package com.zj.osm.view.navigation

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.example.location_library.china_location.ChinaLocation.Companion.getInstance
import com.example.location_library.china_location.ChinaLocationNotifyChange
import com.example.location_library.china_location.ChineLocationBean
import com.example.location_library.china_location.LocationType
import com.example.location_library.map.MapUtil
import com.zj.osm.R
import com.zj.osm.entity.greendao.Point
import com.zj.osm.mvp.MvpActivity
import com.zj.osm.utils.Configuration
import com.zj.osm.utils.MyUtils.Distance
import com.zj.osm.utils.db_utils.PointsUtils.Companion.instance
import com.zj.utils.data.LiveDataBus
import com.zj.utils.map.GoogleTileSource
import com.zj.utils.utils.utilcode.NetworkUtils
import com.zj.utils.utils.utilcode.SPUtils
import com.zj.utils.utils.utilcode.ToastUtils
import kotlinx.android.synthetic.main.activity_navigation.*
import org.osmdroid.api.IMapController
import org.osmdroid.tileprovider.modules.OfflineTileProvider
import org.osmdroid.tileprovider.util.SimpleRegisterReceiver
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.compass.CompassOverlay
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay
import java.lang.ref.SoftReference
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.*


class NavigationActivity : MvpActivity<NavigationActivityView, NavigationActivityPresenter>(), NavigationActivityView, ChinaLocationNotifyChange, View.OnClickListener {
    private var longitude: Double = 0.0
    private var latitude: Double = 0.0
    private var mLocationOverlay: MyLocationNewOverlay? = null//自己当前所在位置
    private var mapController: IMapController? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_navigation)
        initView()
        loadMap()
        initData()
    }

    private fun initView() {
        mainTitleBar.mTitleTv.text = "移动勘测设计导航"
        mainIbLocation.setOnClickListener(this)
        initDialog()

    }

    private fun initDialog() {
        navigat_navi!!.setOnClickListener(this)
    }


    private fun loadMap() {
        //设置地图源
        setMapSources()
        mapController = navigaMap.controller
        mapController!!.setZoom(18.0)
        //缩放按钮
        navigaMap.setBuiltInZoomControls(false)//隐藏掉缩放按钮
        navigaMap.setMultiTouchControls(true)//多只操控。不然只能双击
        this.mLocationOverlay = MyLocationNewOverlay(GpsMyLocationProvider(this), navigaMap)
        this.mLocationOverlay!!.enableMyLocation()
        //定位自己
        getInstance().setContext(this).setLocationType(LocationType.GAO_DE).initLocation()
        val mCompassOverlay = CompassOverlay(this, InternalCompassOrientationProvider(this), navigaMap)
        mCompassOverlay.enableCompass()
        navigaMap.overlays.add(mCompassOverlay)


    }

    private fun initData() {
        LiveDataBus.get().getChannel(Configuration.PROJECT_ID, Long::class.java).observe(this, androidx.lifecycle.Observer { projectId ->
            presenter.getPointsList(projectId)
        })


    }

    override fun createPresenter(): NavigationActivityPresenter {
        return NavigationActivityPresenter()
    }

    override fun createView(): NavigationActivityView {
        return this
    }


    @SuppressLint("SetTextI18n")
    override fun initPoints(pointList: List<Point>) {
        for (index in pointList.indices) {
            addMarker(pointList[index])
        }
        if(pointList.isNotEmpty()){
            pointsFist = pointList[0]
            for (index1 in pointList.indices) {
                if (pointList[index1].legendTypeKey.contains("TY_ZSBYQ")) {
                    pointsFist = pointList[index1]
                    return
                }
            }
            for (index1 in pointList.indices) {
                if (pointList[index1].legendTypeKey.contains("TY_XSBDZ")) {
                    pointsFist = pointList[index1]
                    return
                }
            }
        }else{
            card_visible.visibility=View.GONE

        }


    }

    @SuppressLint("SetTextI18n")
    private fun initNaveItemView() {
        //初始化导航弹窗
        ///计算距离
        var distence = Distance(latitude, longitude, pointsFist!!.latitude, pointsFist!!.longitude)
        if (distence > 1000) {
            navigat_distence!!.text = "距离目的地: ${BigDecimal(distence / 1000).setScale(2, RoundingMode.UP)}km"

        } else {
            navigat_distence!!.text = "距离目的地: ${BigDecimal(distence).setScale(2, RoundingMode.UP)}m"

        }
        navigat_ganxin!!.text = "类型: ${pointsFist!!.name} "
        navigat_number!!.text = "编号:  ${pointsFist!!.mark}"

    }

    private fun addMarker(point: Point) {
        //获取点的Marker
        //获取点的Marker
        val poiMarker = instance.getPointMarker(point, this, navigaMap)
        setMarkerInfoWindow(poiMarker)
        /**
         *这个是杆塔/底薪点/设备的mark名称
         */
        val m = instance.getPointMarkerNameMarker(navigaMap, point, true)
        navigaMap.overlays.add(poiMarker)
    }

    /***
     * 设置Marker点的点击事件
     * @param marker marker
     */
    private fun setMarkerInfoWindow(marker: Marker) {
        /**
         * 如果返回true就消费掉当前事件。
         * 如果返回false会调用map上所有的marker所以onMarkerClick内部会走完所有的事件。
         */
        marker.setOnMarkerClickListener { poiMarker: Marker?, mapView: MapView? ->
            val mMarkerId = marker.id
            if (mMarkerId == null || mMarkerId.isEmpty()) {
                return@setOnMarkerClickListener false
            }
            clickMarker(marker)
            true
        }
    }

    var pointsFist: Point? = null

    //点击切换导航。
    @SuppressLint("SetTextI18n")
    private fun clickMarker(marker: Marker) {
        pointsFist = marker.relatedObject as Point
        ///计算距离
        var distence = Distance(latitude, longitude, pointsFist!!.latitude, pointsFist!!.longitude)
        if (distence > 1000) {
            navigat_distence!!.text = "距离目的地: ${BigDecimal(distence / 1000).setScale(2, RoundingMode.UP)}km"

        } else {
            navigat_distence!!.text = "距离目的地: ${BigDecimal(distence).setScale(2, RoundingMode.UP)}m"

        }
        navigat_ganxin!!.text = "类型: ${pointsFist!!.name} "
        navigat_number!!.text = "编号:  ${pointsFist!!.mark}"
    }


    /**
     * 设置地图源 有网路情况下直接使用网络，没网情况下加载离线地图
     */
    private fun setMapSources() {
        val defaultMapFlag = SPUtils.getInstance().getString("DEFAULT_MAP_FLAG")
        if (defaultMapFlag == "ONLINE_MAP") {
            val mapSource = SPUtils.getInstance().getString(Configuration.MAP_TILE_SOURCE)
            if (!TextUtils.isEmpty(mapSource)) {
                Log.e("resource=", mapSource)
                navigaMap.setTileSource(Objects.requireNonNull(GoogleTileSource.GoogleHybrid))
            }
        } else {
            //ToastUtils.showShort("当前无网络，请选择离线地图包");
            if (navigaMap.getOverlays().size <= 0) {
                //GoogleTileSource.mapViewOtherData("/osmdroid/china.sqlite", new SoftReference<>(this), mMapView);
                val file = GoogleTileSource.mapViewOtherData("/osmdroid/$defaultMapFlag")
                var tileProvider: OfflineTileProvider? = null
                try {
                    tileProvider = OfflineTileProvider(SimpleRegisterReceiver(this), arrayOf(file))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                navigaMap.setTileProvider(tileProvider)
            }
        }
    }


    var isFirstLocation = true
    var address: String = ""
    override fun onReceiveLocation(chinaLocationBean: ChineLocationBean) {
        //只有卫星模式才可以进行。
        latitude = chinaLocationBean.chinaLatitude
        longitude = chinaLocationBean.chinaLongitude
        if (chinaLocationBean.chinaAddress != null) {
            //https://api.map.baidu.com/reverse_geocoding/v3/?ak=z8DbYfMV3Pl7e9mYhYOpWD5Fr2XWIqm6&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194
            address = chinaLocationBean.chinaAddress.toString()
        } else {
            address = ""
        }
        Log.e("dingwei==", "latitude$latitude:longitude$longitude")
        if (latitude > 1 && longitude > 1 && isFirstLocation) {
            isFirstLocation = false
            mapController = navigaMap.controller
            val enen = GeoPoint(latitude, longitude)
            mapController!!.animateTo(enen, navigaMap.zoomLevelDouble, 100L)
            initNaveItemView()
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.navigat_navi -> {//导航开始调用第三方。
                if (address.isEmpty()) {
                    address = "当前位置"
                }
                if (pointsFist != null)
                    MapUtil.startNaviDialogAuto(this, latitude.toString(), longitude.toString(), address, pointsFist!!.latitude.toString(), pointsFist!!.longitude.toString(), pointsFist!!.address);
            }
            R.id.mainIbLocation -> {
                location()
            }
        }
    }

    /**
     * 定位到当前位置
     */
    private fun location() {
        //判空，不然会报错
        if (latitude > 0.0 && longitude > 0.0) {
            val latitude: Double = latitude
            val longitude: Double = longitude
            Log.e("dingwei中心==", "latitude$latitude:longitude$longitude")
            if (latitude > 0 && longitude > 0) {
                mapController = navigaMap.getController()
                mapController!!.setZoom(18.0)
                val startPoint = GeoPoint(latitude, longitude)
                //动画平移到当前位置
                mapController!!.animateTo(startPoint, navigaMap.zoomLevelDouble, 100L)
            }
        } else {
            ToastUtils.showShort("没有获取到当前位置，请稍后重试")
        }
    }

}
